"""
用户授权
1.先给用户添加角色
2。给角色添加权限
3.操作--> 用户角色表和角色权限表
"""
from pymysqlutil import MysqlUtil


class UserRoleManager:
    def __init__(self):
        self.mysqlutil = MysqlUtil("db_qxgl")

    def add_role(self):
        """
        查询当前角色
        :return:
        """
        sql = "select * from tb_role"
        datas = self.mysqlutil.query_all(sql)
        for data in datas:
            print("角色展示：", data)
        sql = "select * from tb_user"
        datas = self.mysqlutil.query_all(sql)
        for data in datas:
            print("用户展示：", data)
        id1 = int(input("请输入需要添加角色的用户id："))
        id2 = int(input("请输入要添加的角色id："))
        sql = "insert into tb_user_role(userid,roleid)values(%s,%s)"
        args = (id1, id2)
        result = self.mysqlutil.operator_data(sql, args)
        if result == 1:
            print("添加角色成功")
        else:
            print("添加角色失败")

    def add_menu(self):
        sql = "select * from tb_role"
        datas = self.mysqlutil.query_all(sql)
        for data in datas:
            print("角色展示：", data)
        sql = "select * from tb_menu"
        datas = self.mysqlutil.query_all(sql)
        for data in datas:
            print("权限展示：", data)
        id1 = int(input("请输入需要添加权限的角色id："))
        id2 = int(input("请输入要添加的权限id："))
        sql = "insert into tb_role_menu(roleid, menuid)values(%s,%s)"
        args = (id1, id2)
        result = self.mysqlutil.operator_data(sql, args)
        if result == 1:
            print("添加权限成功")
        else:
            print("添加权限失败")

    def select_menu(self):
        """
        查询用户权限
        :return:
        """
        uid = int(input("请输入要查询权限的用户id："))
        sql = f"select u.id,u.username,r.rolename,m.menuname from tb_user u,tb_user_role ur,tb_role_menu rm,tb_menu m,tb_role r where u.id=ur.userid and ur.roleid=rm.roleid and rm.menuid=m.id and ur.roleid=r.id and u.id={uid}"
        datas = self.mysqlutil.query_all(sql)
        if len(datas) > 0:
            for data in datas:
                print(data)
        else:
            print("当前用户未曾授权！")
    def show_menu(self):
        menu = """
        1.添加角色
        2.添加权限
        3.查询权限
        0.退出授权
        """
        print(menu)

    def operator(self):
        while True:
            self.show_menu()
            num = int(input("请输入数字选择操作："))
            if num == 1:
                print("给用户添加角色")
                self.add_role()
            elif num == 2:
                print("给角色添加权限")
                self.add_menu()
            elif num == 3:
                print("查询用户具有的权限")
                self.select_menu()
            elif num == 0:
                print("退出用户授权")
                break
            else:
                print("您输入的选择不存在！")
                continue



